var dbmodel = require("../model/dbmodel");
var bcrypt = require("../config/bcrypt");
var jwt = require("../config/jwt");
const { promises } = require("stream");
const { promisify } = require("util");

//新用户注册
exports.userAsign = function(name,psw,email,res){//新用户注册
    let password = bcrypt.bcryption(psw);
    let options = {
        name:name,
        psw:password,
        email:email,
        time:new Date()
    }
    let user = new dbmodel.users(options);
    user.save((err,result)=>{
        if(err){
            res.send({status:500,err})
        }else{
            res.send({status:200,data:result})
        }
    })
}
//匹配用户表元素个数
exports.countUserValue = function(data,type,res){
    let wherestr = {}
    wherestr[type] = data
    dbmodel.users.countDocuments(wherestr,(err,result)=>{
        if(err){
            res.send({status:500})
        }else{
            res.send({status:200,data:result})
        }
    })
}
//用户验证
exports.userLogin = function(data,psw,res){
    let wherestr = {$or:[{name:data},{email:data}]};//或的搜索
    let out = {name:1,psw:1,imgurl:1,email:1}
    dbmodel.users.find(wherestr,out,(err,result)=>{
        if(err){
            res.send({status:500,err})
        }else{
        //    console.log(result);
            if(result == ''){
                res.send({status:400,err:'用户名或密码错误,未找到数据'})
            }else{
                result.map((item)=>{
                    var matchpsw = bcrypt.verification(psw,item.psw);//判断数据库中的哈希密码与实际上输的密码是否一致
                    if(matchpsw){
                        let token = jwt.createToken(item._id);//生成token
                        let info = {
                            id:item._id,
                            name:item.name,
                            imgurl:item.imgurl,
                            email:item.email,
                            token
                        }
                        res.send({status:200,data:info})
                    }else{
                        res.send({status:400,err:'用户名或密码错误，密码错误'})
                    }
                })
            }
        }
    })
}

//搜索用户
function searchUser(data,res){
    return new Promise((resolve,reject)=>{
        let wherestr = {$or:[{name:{$regex:data}},{email:{$regex:data}}]};//模糊匹配
        let out = {name:1,imgurl:1,email:1}
        dbmodel.users.find(wherestr,out,(err,result)=>{
            if(err){
                reject({status:500,err})
            }else{
                resolve(result)
            }
        })
    })
}
//搜索判断是否为好友
function searchIsFriend(uid,fid,res){
    return new Promise((resolve,reject)=>{
        let wherestr = {userID:uid,friendID:fid,state:0};
        dbmodel.friends.countDocuments(wherestr,(err,result)=>{
            if(err){
                reject({status:500,err})
            }else{
                resolve(result)    
            }
        })
    }) 
}
//判断是否为好友
exports.isFriend = function(uid,fid,res){
    let wherestr = {userID:uid,friendID:fid,state:0};
    dbmodel.friends.findOne(wherestr,(err,result)=>{
        if(err){
            res.send({status:500,err})
        }else{
            if(result != ''){
                //是好友
                res.send({status:200,data:result})
            }else{
                //不是好友
                res.send({status:400,data:result})
            }
            
        }
    })
}
//搜索群
function searchGroup(data,res){
    return new Promise((resolve,reject)=>{
        let wherestr = {name:{$regex:data}};//模糊匹配
        let out = {name:1,imgurl:1}
        dbmodel.groups.find(wherestr,out,(err,result)=>{
            if(err){
                reject({status:500,err})
            }else{
                
                resolve(result)
            }
        })
    })
}
//搜索判断是否在群内
function searchIsInGroup(uid,gid,res){
    return new Promise((resolve,reject)=>{
        let wherestr = {userID:uid,groupID:gid};
        dbmodel.groupusers.countDocuments(wherestr,(err,result)=>{
            if(err){
                reject({status:500,err})
            }else{
                resolve(result)             
            }
        })
    })
}


//判断是否在群内
exports.isInGroup = function(uid,gid,res){
    let wherestr = {userID:uid,groupID:gid};
    dbmodel.groupusers.findOne(wherestr,(err,result)=>{
        if(err){
            res.send({status:500,err})
        }else{
            if(result != ''){
                //在群内
                res.send({status:200,data:result})
            }else{
                //不在群内
                res.send({status:400,data:result})
            }
            
        }
    })
}
//搜索用户和群并判断是否为好友或是否在群内
async function searchInfo(data,res){
    let users,groups,result,err;//保存用户列表，群列表
    [users,err] = await searchUser(data.key).then(mydata=> [mydata,err]).catch(err => [null,err])
    var userlist = users.map(async (item)=>{
        [result,err] = await searchIsFriend(data.uid,item._id).then(mydata=> [mydata,err]).catch(err => [null,err])
        let myitem = {
            imgurl: item.imgurl,
            _id: item._id,
            name:item.name,
            email: item.email
        }
        if(result == 0){
            myitem.isfriend = false
        }else{
            myitem.isfriend = true
        }
        return myitem;     
    })
    userlist = await Promise.all(userlist);//注意点哦
    [groups,err] = await searchGroup(data.key).then(mydata => [mydata,null]).catch(err => [null,err])
    let grouplist = groups.map(async (item)=>{
        let [result,err] =await searchIsInGroup(data.uid,item._id).then(mydata => [mydata,null]).catch(err => [null,err])
        let myitem = {
            imgurl: item.imgurl,
            _id: item._id,
            name:item.name,
        }
        if(result == 0){
            myitem.isingroup = false
        }else{
            myitem.isingroup = true
        }
        return myitem
    })
    grouplist = await Promise.all(grouplist)
    if(err){
        res.send({status:500,err})
    }else{
        res.send({status:200,data:{userlist,grouplist}})
    }
}

exports.searchInfo = function(data,res){
    searchInfo(data,res)
}

//一次性查询用户详情并返回是否为好友还是陌生人
function detail(fid){
    return new Promise((resolve,reject)=>{
        let wherestr = {_id:fid};
        // let outstr = {email:1,imgurl:1,name:1,sex:1,time:1,desc:1,birthday,}
        dbmodel.users.findOne(wherestr,(err,result)=>{
            if(err){
                reject(err)
            }else{
                resolve(result)
            }
        })
    })
}
function getmarkname(uid,fid,res){//一次性获取昵称
    return new Promise((resolve,reject)=>{
        let wherestr = {userID:uid,friendID:fid}
        let out = {markname:1}
        dbmodel.friends.findOne(wherestr,out,(err,result)=>{
            if(err){
                reject(err)
            }else{
                resolve(result)
            }
        })
    })
}
async function judgefrienddetail(uid,fid,res){
    let count,result,markname,err,myresult
    if(uid != fid){
        [count,err] = await searchIsFriend(uid,fid).then(data => [data,null]).catch(err => [null,err]);
        [result,err] = await detail(fid).then(data => [data,null]).catch(err => [null,err]);
        myresult = JSON.parse(JSON.stringify(result));
        if(count != 0){
            myresult.isfriend = 1;//是好友
            [markname,err] = await getmarkname(uid,fid).then(data => [data,null]).catch(err => [null,err]);
            if(markname.markname == undefined){
                myresult.markname = result.name;
            }else{
                myresult.markname = markname.markname
            }
        }else{
            myresult.isfriend = 2;//不是好友
            myresult.markname = result.name;
        }
    }else{
        [result,err] = await detail(fid).then(data => [data,null]).catch(err => [null,err]);   
        myresult = JSON.parse(JSON.stringify(result));
        myresult.isfriend = 0;//是本人
        myresult.markname = result.name;
    }
    if(err){
        res.send({status:500})
    }else{
        res.send({status:200,data:myresult})
    }
    
} 
exports.userDetail = function(uid,fid,res){
    judgefrienddetail(uid,fid,res)
}
//查看用户详情
// exports.userDetail = function(fid,res){
//     let wherestr = {_id:fid};
//     dbmodel.users.findOne(wherestr,(err,result)=>{
//         if(err){
//             res.send({status:500,err})
//         }else{
//             res.send({status:200,data:result})
//         }
//     })
// }
//用户信息修改(包括密码的修改)
exports.userUpdate = function(data,res){
    let updatestr = {}
    if(data.pwd != undefined){//对用户信息密码的修改
        let wherestr = {_id:data.id};
        dbmodel.users.find(wherestr,{psw:1},(err,result)=>{//通过ID和编码过的密码进行查询对应的用户
            if(err){
                res.send({status:500,err})
            }else{
                if(result != ''){
                    result.map((item)=>{                       
                        var matchpsw = bcrypt.verification(data.pwd,item.psw);//判断数据库中的哈希密码与实际上输的密码是否一致
                        if(matchpsw){
                            if(data.type === 'email'){
                                updatestr[data.type] = data.data;//邮箱修改时需要提前判断邮箱是否已经存在重复
                                dbmodel.users.countDocuments({email:data.data},(err,result)=>{
                                    if(err){
                                        res.send({status:500,err});
                                    }else{
                                        if(result == 0){
                                            update(data.id,updatestr,res);
                                        }else{
                                            res.send({status:600});//邮箱重复了
                                        }
                                    }
                                })
                            }else{
                                let bcryptpsw = bcrypt.bcryption(data.data);//编码过后的密码
                                updatestr[data.type] = bcryptpsw;
                                update(data.id,updatestr,res); 
                            }                                   
                        }else{
                            res.send({status:100})//密码错误
                        }
                    })
                }else{
                    res.send({status:400})//没有该用户信息
                }
            }
        })
    }else if(data.type == 'name'){//用户名修改时需要提前判断用户名是否已经存在重复
        updatestr[data.type] = data.data;
        dbmodel.users.countDocuments({email:data.data},(err,result)=>{
            if(err){
                res.send({status:500,err})
            }else{
                if(result == 0){
                    update(data.id,updatestr,res);
                }else{
                    res.send({status:400})//用户名存在重复
                }
            }
        })
    }
    else{
    //    console.log(updatestr)
        updatestr[data.type] = data.data;
        update(data.id,updatestr,res);
    }
}
function update(date,updatestr,res){//根据id值修改数据库
    dbmodel.users.findByIdAndUpdate(date,updatestr,(err,result)=>{
        if(err){
            res.send({status:500,err})
        }else{
            res.send({status:200,data:result})
        }
    })
}
//获取用户昵称
exports.getFriendMarkName = function(data,res){
    let wherestr = {userID:data.uid,friendID:data.fid}
    let out = {markname:1}
    dbmodel.friends.findOne(wherestr,out,(err,result)=>{
        if(err){
            res.send({status:500,err})
        }else{
            res.send({status:200,data:result})
        }
    })
}

//用户昵称的修改
exports.updateFriendMarkName = function(data,res){
    let updatestr = {markname:data.markname}
    let wherestr = {userID:data.uid,friendID:data.fid}
    dbmodel.friends.updateOne(wherestr,updatestr,(err,result)=>{
        if(err){
            res.send({status:500,err})
        }else{
            res.send({status:200,data:result})
        }
    })
}
//添加好友信息表
exports.createFriend = function(uid,fid,state,res){
    let options = {
        userID:uid,
        friendID:fid,
        state:state,
        time:new Date(),
        lasttime:new Date()
    }
    let friend = new dbmodel.friends(options);
    friend.save((err,result)=>{
        if(err){
            console.log("添加好友信息表失败")
        }else{
            // res.send({status:200,data:result})
        }
    })
}
//好友表最新的通讯时间
exports.upFriendLastTime = function(uid,fid){
    let wherestr = {$or:[{userID:uid,friendID:fid},{userID:fid,friendID:uid}]}
    let updatestr = {lasttime:new Date()}
    dbmodel.friends.updateMany(wherestr,updatestr,(err,result)=>{
        if(err){
            console.log("好友表最新的通讯时间失败")
        }else{
            // res.send({status:200,data:result})
        }
    })
}


//添加一对一信息表
exports.insertMsg = function(uid,fid,message,types,res){
    let options = {
        userID:uid,
        friendID:fid,
        message:message,
        types:types,
        state:1,
        time:new Date()
    }
    let messages = new dbmodel.messages(options);
    messages.save((err,result)=>{
        if(err){
            // res.send({status:500,err})
        }else{
           let wherestr = {$or:[{userID:uid,friendID:fid},{userID:fid,friendID:uid}]};
           let updatastr = {lasttime:new Date()};
           dbmodel.friends.updateMany(wherestr,updatastr,(err,myresult)=>{
                if(err){
                    // res.send({status:500,err})
                }else{
                    // console.log(myresult)
                }
           })
        }
    })
}

//申请添加好友
exports.applyFriend = function(data,res){
    let wherestr = {userID:data.uid,friendID:data.fid};
    dbmodel.friends.countDocuments(wherestr,(err,result)=>{
        if(err){
            res.send({status:500,err})
        }else{
            //之前没有申请信息
            if(result === 0){
                this.createFriend(data.uid,data.fid,2)
                this.createFriend(data.fid,data.uid,1)
                res.send({status:200})
            }else{//之前有申请信息
                this.upFriendLastTime(data.uid,data.fid)
                res.send({status:200})
            }
            this.insertMsg(data.uid,data.fid,data.message,0,res)
        }
    })
}
//更新好友状态(同意)
exports.updateFriendState = function(data,res){
    let updatestr = {state:0};
    let wherestr = {$or:[{userID:data.uid,friendID:data.fid},{userID:data.fid,friendID:data.uid}]};
    dbmodel.friends.updateMany(wherestr,updatestr,(err,result)=>{
        if(err){
            res.send({status:500,err})
        }else{
            res.send({status:200,data:result})
        }
    })
}

//拒绝好友删除好友
exports.deleteFriend = function(data,res){
    let wherestr = {$or:[{userID:data.uid,friendID:data.fid},{userID:data.fid,friendID:data.uid}]};
    dbmodel.friends.deleteMany(wherestr,(err,result)=>{
        if(err){
            res.send({status:500,err})
        }else{
            res.send({status:200,data:result})
        }
    })
}



/*废除的方法getUsers
//按要求搜索用户列表(主页)
exports.getUsers = function(data,res){
    let query = dbmodel.friends.find({});
    //查询条件
    query.where({userID:data.uid,state:data.state});
    //查找friendID关联的userd对象,这样可以访问到关联表中对应的数据
    query.populate('friendID')
    //时间排序，通讯时间倒序(-1为倒序)
    query.sort({lasttime:-1})
    query.exec().then((result)=>{
        let list = result.map((item)=>{
            let option = {
                id:item.friendID._id,//查询friendID关联到users表中的id数据
                name:item.friendID.name,//查询friendID关联到users表中的name数据
                markname:item.markname,
                imgurl:item.friendID.imgurl,//查询friendID关联到users表中的imgurl数据
                lasttime:item.lasttime
            }
            return option
        })    
        res.send({status:200,data:list})
    }).catch((err)=>{
        res.send({status:500,err})
    })
}
//按要求获取一对一消息
exports.getOneMsg = function(data,res){
    let query = dbmodel.messages.findOne({});
    //查询条件
    query.where({$or:[{userID:data.uid,friendID:data.fid},{userID:data.fid,friendID:data.uid}]});
    //时间排序，通讯时间倒序(-1为倒序)
    query.sort({time:-1})
    query.exec().then((result)=>{
        let option = {
            message:result.message,
            time:result.time,
            types:result.types,
        }
        res.send({status:200,data:option})
    }).catch((err)=>{
        res.send({status:500,err})
    })
}
//获取未读消息数
exports.unreadMsg = function(data,res){
    let wherestr = {userID:data.uid,friendID:data.fid,state:data.state};
    dbmodel.messages.countDocuments(wherestr,(err,result)=>{
        if(err){
            res.send({status:500,err})
        }else{
            res.send({status:200,data:result})
        }
    })
}
*/

//首页一次性获取好友列表，未读消息数，最新的消息
function getUser(data,res){
    return new Promise((resolve,reject)=>{
        let querry = dbmodel.friends.find({})
        querry.where({userID:data.uid,state:data.state})
        querry.populate('friendID')
        querry.exec().then((result)=>{
            let list = result.map((item)=>{
                let option = {
                    id:item.friendID._id,//查询friendID关联到users表中的id数据
                    name:item.friendID.name,//查询friendID关联到users表中的name数据
                    markname:item.markname,
                    imgurl:item.friendID.imgurl,//查询friendID关联到users表中的imgurl数据
                    lasttime:item.lasttime
                }
                return option
                
            }) 
            resolve(list)

        }).catch((err)=>{
            reject({status:500,err})
        })
    })
}
//按要求获取一对一消息
function getOneMsg(uid,fid,res){
    return new Promise((resolve,reject)=>{
        let query = dbmodel.messages.findOne({});
        //查询条件
        query.where({$or:[{userID:uid,friendID:fid},{userID:fid,friendID:uid}]});
        //时间排序，通讯时间倒序(-1为倒序)
        query.sort({time:-1})
        query.exec().then((result)=>{
            let option = {
                message:result.message,
                time:result.time,
                types:result.types,
            }
            resolve(option)
        }).catch((err)=>{
            reject({status:500,err})
        })
    })
}
//获取未读消息数
function unreadMsg(uid,fid,res){
    return new Promise((resolve,reject)=>{
        let wherestr = {userID:fid,friendID:uid,state:1};
        dbmodel.messages.countDocuments(wherestr,(err,result)=>{
            if(err){
                reject({status:500,err})
            }else{
                resolve(result)
            }
        })
    })
    
}
//一次性获取首页好友内容
async function getuserinfolist(data,res){
    let friend,aa,bb,err;
    [friend,err] = await getUser(data,res).then(data => [data,null]).catch(err => [null,err]);
    for(var i = 0;i<friend.length;i++)   
    {
        [aa,err] = await getOneMsg(data.uid,friend[i].id).then(data => [data,null]).catch(err => [null,err]);
        if(aa.types === 0){

        }else if(aa.types === 1){
            aa.message = "[图片]"
        }else if(aa.types === 2){
            aa.message = "[语音]"
        }else if(aa.types === 3){
            aa.message = "[位置]"
        }
        friend[i].message =  aa.message;
        [bb,err] = await unreadMsg(data.uid,friend[i].id).then(data => [data,null]).catch(err => [null,err]);
        friend[i].tip = bb;
        friend[i].tap = 0;
    }
    if(err){
        reject({status:500,err})
    }else{
    //    console.log(friend)
        res.send({status:200,data:friend})
    }
}

exports.getUsers = function(data,res){
    getuserinfolist(data,res)
}


//修改信息已读未读状态
exports.updateMsg = function(data,res){
    // console.log(data)
    let wherestr = {userID:data.fid,friendID:data.uid,state:'1'};
    let updatestr = {state:'0'}
    dbmodel.messages.updateMany(wherestr,updatestr,(err,result)=>{
        if(err){
            res.send({status:500,err})
        }else{
            res.send({status:200,data:result})
        }
    })
}
/*废弃的建群方法
//建群以及添加群成员
// exports.cteateGroup = function(data,res){
//     let options = {
//         userID:data.uid,
//         name:data.name,
//         imgurl:data.imgurl,
//         time:new Date()
//     }
//     let groups = new dbmodel.groups(options);
//     groups.save((err,result)=>{
//         if(err){
//             res.send({status:500,err})
//         }else{       
//             dbmodel.groups.find({userID:data.uid,name:data.name},{_id:1},(err,myresult)=>{
//                 if(err){
//                     res.send({status:500,err})
//                 }else{
//                     myresult.map((item)=>{
//                         let _id = item._id;
//                         //加入群主
//                         let uinfo = {
//                             groupID:_id,
//                             userID:data.uid,
//                             time:new Date(),
//                             lasttime:new Date(),
//                         }
//                         this.addGroupUser(uinfo,res)
//                         //加入好友
//                         data.list.map((e)=>{
//                             let finfo = {
//                                 groupID:_id,
//                                 userID:e.uid,
//                                 time:new Date(),
//                                 lasttime:new Date(),
//                             }
//                             this.addGroupUser(finfo,res)
//                         })
//                     })
//                     res.send({status:200})
//                 }
//             })
//         }
//     })
// }
*/

//建群以及添加群成员
exports.cteateGroup = function(data,res){
    return new Promise((resolve,reject)=>{
        let options = {
            userID:data.uid,
            name:data.name,
            imgurl:data.imgurl,
            time:new Date()
        }
        let groups =  new dbmodel.groups(options);
        groups.save((err,result)=>{
            if(err){
                reject({status:500,err})
            }else{   
                resolve({result,data})
            }
        })
    }).then((value)=>{   
        let myresult = value.result
        let mydata = value.data
        
        for(var i = 0;i<mydata.myusers.length;i++){
            let fdata = {
                groupID:myresult._id,
                userID:mydata.myusers[i],
                time:new Date(),
                lasttime:new Date(),
            }
            this.myaddGroupUser(fdata,res)//添加群成员
        }
        res.send({status:200})
    }).catch((err)=>{
        res.send({status:500})
    })
}
//解散群以及删除群成员
exports.deleteGroup = function(data,res){
    let wherestr = {groupID:data.gid};
    dbmodel.groupusers.deleteMany(wherestr,(err,result)=>{
        if(err){
            res.send({status:500})
        }else{
            wherestr = {'_id':data.gid};
            dbmodel.groups.deleteOne(wherestr,(err,myresult)=>{
                if(err){
                    res.send({status:500})
                }else{
                    res.send({status:200})
                }
            })
        }
    })
}
//用户退出群
exports.outGroup = function(data,res){
    let wherestr = {groupID:data.gid,userID:data.uid};
    dbmodel.groupusers.deleteOne(wherestr,(err,result)=>{
        if(err){
            res.send({status:500})
        }else{
            res.send({status:200})
        }
    })
}


//添加群成员
exports.myaddGroupUser = function(data,res){
    let groupusers = new dbmodel.groupusers(data);
    groupusers.save((err,result)=>{
        if(err){
            res.send({status:500})
        }else{
            // res.send({status:200})
            console.log('添加成功')
        }
    })
}
//添加群成员
exports.addGroupUser = function(data,res){
    let groupusers = new dbmodel.groupusers(data);
    groupusers.save((err,result)=>{
        if(err){
            res.send({status:500})
        }else{
            res.send({status:200})
        }
    })
}
//删除群成员
exports.deleteGroupUser = function(data,res){
    let wherestr = {groupID:data.gid,userID:data.uid};
    dbmodel.groupusers.deleteOne(wherestr,(err,result)=>{
        if(err){
            res.send({status:500})
        }else{
            res.send({status:200})
        }
    })
    
}
//群个人信息获取
exports.groupUserInfo = function(data,res){
    let wherestr = {groupID:data.gid,userID:data.uid}
    dbmodel.groupusers.findOne(wherestr,(err,result)=>{
        if(err){
            res.send({status:500,err})
        }else{
            res.send({status:200,data:result})
        }
    })  
}

//群信息修改
exports.groupUpdate = function(data,res){
    let updatestr = {};
    let wherestr = {'_id':data.gid}
    updatestr[data.type] = data.data;
    dbmodel.groups.updateOne(wherestr,updatestr,(err,result)=>{
        if(err){
            res.send({status:500,err})
        }else{
            res.send({status:200})
        }
    })  
}

//群个人信息修改
exports.groupUserUpdate = function(data,res){
    let wherestr = {groupID:data.gid,userID:data.uid}
    let updatestr = {};
    updatestr[data.type] = data.data;
    dbmodel.groupusers.updateOne(wherestr,updatestr,(err,result)=>{
        if(err){
            res.send({status:500,err})
        }else{
            res.send({status:200,data:result})
        }
    })  
}
/*
//按要求获取群列表数据
exports.getGroups = function(data,res){
    let query = dbmodel.groupusers.find({});
    //查询条件
    query.where({userID:data.uid});
    //查找groupID关联的group对象,这样可以访问到关联表中对应的数据
    query.populate('groupID')
    //时间排序，通讯时间倒序(-1为倒序)
    query.sort({lasttime:-1})
    query.exec().then((result)=>{
        let list = result.map((item)=>{
            let option = {
                id:item.groupID._id,//查询groupID关联到groups表中的id数据
                name:item.groupID.name,//查询groupID关联到groups表中的name数据
                markname:item.name,//群内名
                imgurl:item.groupID.imgurl,//查询groupID关联到groups表中的imgurl数据
                lasttime:item.lasttime,
                tip:item.tip//群未读消息数
            }
            return option
        })    
        res.send({status:200,data:list})
    }).catch((err)=>{
        res.send({status:500,err})
    })
}

//按要求获取群最后一条消息
exports.getOneGropmsg = function(data,res){
    let query = dbmodel.groupmessages.findOne({});
    //查询条件
    query.where({groupID:data.gid});
    //时间排序，通讯时间倒序(-1为倒序)
    query.populate('userID')
    query.sort({time:-1})
    query.exec().then((result)=>{
        let option = {
            name:result.userID.name,//显示是谁发送的
            message:result.message,
            time:result.time,
            types:result.types,
        }
        res.send({status:200,data:option})
    }).catch((err)=>{
        res.send({status:500,err})
    })
}
*/

//按要求获取群列表数据
function mygetGroups(data,res){
    return new Promise((resolve,reject)=>{
        let query = dbmodel.groupusers.find({});
        //查询条件
        query.where({userID:data.uid});
        //查找groupID关联的group对象,这样可以访问到关联表中对应的数据
        query.populate('groupID')
        //时间排序，通讯时间倒序(-1为倒序)
        query.sort({lasttime:-1})
        query.exec().then((result)=>{
            let list = result.map((item)=>{
                let option = {
                    id:item.groupID._id,//查询groupID关联到groups表中的id数据
                    name:item.groupID.name,//查询groupID关联到groups表中的name数据
                    markname:item.name,//群内名
                    imgurl:item.groupID.imgurl,//查询groupID关联到groups表中的imgurl数据
                    lasttime:item.lasttime,
                    tip:item.tip//群未读消息数
                }
                return option
            })    
            resolve(list)
        }).catch((err)=>{
            reject({status:500,err})
        })
    })
}
//通过gid获取群详细信息以及群成员
async function groupDetail(data,res){
    let totalinfo,mylist,err;
    [mylist,err] = await _this.getGroupUsers(data.gid,res).then(data => [data,null]).catch(err => [null,err])
    let whehestr = {'_id':data.gid}
    dbmodel.groups.findOne(whehestr,(err,result)=>{
        if(err){
            res.send({status:500,err})
        }else{
            totalinfo = JSON.parse(JSON.stringify(result));
            if(mylist.length > 0){
                totalinfo.list = mylist
            }
            res.send({status:200,data:totalinfo})
        }
    })
}
exports.groupDetail = function(data,res){
    groupDetail(data,res)
}
//通过群Id获取群成员
exports.getGroupUsers = function(gid,res){
    return new Promise((resolve,reject)=>{
        let querry = dbmodel.groupusers.find({});
        //通过gid查询群信息
        querry.where({groupID:gid});
        //关联到用户表
        querry.populate('userID');
        //对加入群进行时间的倒序
        querry.sort({time:-1});
        querry.exec().then((result)=>{
            let list = result.map((item)=>{
                let option = {
                    id:item.userID._id,//查询userID关联到users表中的id数据
                    name:item.userID.name,
                    imgurl:item.userID.imgurl,//查询groupID关联到groups表中的imgurl数据
                }
                  
                return option
            })            
            resolve(list)
        }).catch((err)=>{
            reject({status:500,err})
        })
    })
}


//按要求获取群最后一条消息
function getOneGropmsg(gid,res){
    return new Promise((resolve,reject)=>{
        let query = dbmodel.groupmessages.findOne({});
        //查询条件
        query.where({groupID:gid});
        //时间排序，通讯时间倒序(-1为倒序)
        query.populate('userID')
        query.sort({time:-1})
        query.exec().then((result)=>{
            let option = {
                name:result.userID.name,//显示是谁发送的
                message:result.message,
                time:result.time,
                types:result.types,
            }
            resolve(option)
        }).catch((err)=>{
            reject({status:500,err})
        })
    })
    
}
let _this = this;

//获取群列表信息
async function getGroupInfoList(data,res){
    let group,aa,list,err;
    [group,err] = await mygetGroups(data,res).then(data => [data,null]).catch(err => [null,err]);
    for(var i = 0;i<group.length;i++){
        [aa,err] = await getOneGropmsg(group[i].id).then(data => [data,null]).catch(err => [null,err]);
        if(aa){
            if(aa.types === 0){

            }else if(aa.types === 1){
                aa.message = "[图片]"
            }else if(aa.types === 2){
                aa.message = "[语音]"
            }else if(aa.types === 3){
                aa.message = "[位置]"
            }
            group[i].msg =  aa.message;
            group[i].msgname = aa.name;
        }        
        [list,err] = await _this.getGroupUsers(group[i].id,res).then(data => [data,null]).catch(err => [null,err])
        group[i].userlist = list;     
        group[i].tap = 1;
    }
    if(err){
        res.send({status:500,err})
    }else{
        // console.log(group)
        res.send({status:200,data:group})
    }
}
exports.getGroups = function(data,res){
    getGroupInfoList(data,res)
}
//写入群消息(并且更改除了发送者自己的群成员表中的未读消息数和最后消息时间)
exports.insertGroupMsg = function(tid,uid,data,type,res){
    let options = {
        groupID:tid,
        userID:uid,
        message:data,
        types:type,
        time:new Date()
    }
    let groupmessages = new dbmodel.groupmessages(options);
    groupmessages.save((err,result)=>{
        if(err){
            // res.send({status:500,err})
        }else{
           let wherestr = {userID:{$ne:uid},groupID:tid};
           let updatestr = {lasttime:new Date(),$inc:{tip:1}}//用来增加指定字段的数量
           dbmodel.groupusers.updateMany(wherestr,updatestr,(err,myresult)=>{
                if(!err){
                    // console.log(myresult)
                }
           })
        }
    })
}


//修改群信息未读数
exports.updateGroupmsg = function(data,res){
    let wherestr = {userID:data.uid,groupID:data.fid};
    let updatestr = {tip:0}
    dbmodel.groupusers.updateMany(wherestr,updatestr,(err,result)=>{
        if(err){
            res.send({status:500,err})
        }else{
            res.send({status:200,data:result})
        }
    })
}

//消息操作
//分页获取数据一对一聊天数据
//一对一聊天
exports.msg = function(data,res){
    //data : uid fid nowpage pagesize
    var skippagenum = data.nowpage * data.pagesize//跳过的条数
    let querry = dbmodel.messages.find({})
    querry.where({$or:[{userID:data.uid,friendID:data.fid},{userID:data.fid,friendID:data.uid}]})
    querry.populate('userID')
    querry.sort({time:-1})
    //跳过的条数
    querry.skip(skippagenum)
    //一页条数
    querry.limit(data.pagesize)
    querry.exec().then((result)=>{
        let info = result.map((item)=>{
            return {
                id:item._id,
                message:item.message,
                types:item.types,
                time:item.time,
                fromId:item.userID._id,
                imgurl:item.userID.imgurl,
            }
        })
        res.send({status:200,data:info})
    }).catch((err)=>{
        res.send({status:500,err})
    })
}
//群聊天
exports.groupmsg = function(data,res){
    //data : uid fid nowpage pagesize
    var skippagenum = data.nowpage * data.pagesize//跳过的条数
    let querry = dbmodel.groupmessages.find({})
    querry.where({groupID:data.fid})
    querry.populate('userID')
    querry.sort({time:-1})
    //跳过的条数
    querry.skip(skippagenum)
    //一页条数
    querry.limit(data.pagesize)
    querry.exec().then((result)=>{
        let info = result.map((item)=>{
            return {
                id:item._id,
                message:item.message,
                types:item.types,
                time:item.time,
                fromId:item.userID._id,
                imgurl:item.userID.imgurl,
            }
        })
        res.send({status:200,data:info})
    }).catch((err)=>{
        res.send({status:500,err})
    })
}
